//
//  MainViewController.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/14.
//

import UIKit
import Alamofire

class MainViewController: BaseViewController {
    
    private let tableView = UITableView()
    private var logs: [String] = []
    private let domainStatusView = UIView()
    private let domainIndicator = UILabel()
    private let resetButton = UIButton(type: .system)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupNotifications()
        addLog("应用启动，准备进行网络请求")
        updateDomainIndicator()
    }
    
    private func setupUI() {
        title = "多域名无感切换"
        view.backgroundColor = .systemBackground
        
        // 设置域名状态视图
        domainStatusView.backgroundColor = .secondarySystemBackground
        domainStatusView.layer.cornerRadius = 12
        view.addSubview(domainStatusView)
        domainStatusView.translatesAutoresizingMaskIntoConstraints = false
        
        domainIndicator.text = "当前域名: \(DomainManager.shared.currentDomain)"
        domainIndicator.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        domainIndicator.textAlignment = .center
        domainStatusView.addSubview(domainIndicator)
        domainIndicator.translatesAutoresizingMaskIntoConstraints = false
        
        // 设置重置按钮
        resetButton.setTitle("重置域名", for: .normal)
        resetButton.addTarget(self, action: #selector(resetDomains), for: .touchUpInside)
        resetButton.backgroundColor = .systemGray
        resetButton.setTitleColor(.white, for: .normal)
        resetButton.layer.cornerRadius = 8
        domainStatusView.addSubview(resetButton)
        resetButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 设置表格视图
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        
        tableView.register(LogCell.self, forCellReuseIdentifier: "LogCell")
        tableView.dataSource = self
        tableView.delegate = self
        
        // 设置按钮
        let buttonStack = UIStackView()
        buttonStack.axis = .horizontal
        buttonStack.spacing = 16
        buttonStack.distribution = .fillEqually
        view.addSubview(buttonStack)
        buttonStack.translatesAutoresizingMaskIntoConstraints = false
        
        let userButton = createButton(title: "获取用户信息", color: .systemBlue, action: #selector(fetchUserProfile))
        let productsButton = createButton(title: "获取商品", color: .systemGreen, action: #selector(fetchProducts))
        let failButton = createButton(title: "失败请求", color: .systemRed, action: #selector(makeFailingRequest))
        
        buttonStack.addArrangedSubview(userButton)
        buttonStack.addArrangedSubview(productsButton)
        buttonStack.addArrangedSubview(failButton)
        
        NSLayoutConstraint.activate([
            domainStatusView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
            domainStatusView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            domainStatusView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
            domainStatusView.heightAnchor.constraint(equalToConstant: 50),
            
            domainIndicator.centerYAnchor.constraint(equalTo: domainStatusView.centerYAnchor),
            domainIndicator.leadingAnchor.constraint(equalTo: domainStatusView.leadingAnchor, constant: 16),
            domainIndicator.trailingAnchor.constraint(equalTo: resetButton.leadingAnchor, constant: -8),
            
            resetButton.centerYAnchor.constraint(equalTo: domainStatusView.centerYAnchor),
            resetButton.trailingAnchor.constraint(equalTo: domainStatusView.trailingAnchor, constant: -16),
            resetButton.widthAnchor.constraint(equalToConstant: 80),
            
            buttonStack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16),
            buttonStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
            buttonStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
            buttonStack.heightAnchor.constraint(equalToConstant: 50),
            
            tableView.topAnchor.constraint(equalTo: domainStatusView.bottomAnchor, constant: 16),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: buttonStack.topAnchor, constant: -16)
        ])
    }
    
    private func createButton(title: String, color: UIColor, action: Selector) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        button.backgroundColor = color
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 10
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }
    
    private func setupNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(domainSwitched(_:)),
            name: .domainSwitched,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(requestSucceeded),
            name: .requestSucceeded,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(requestFailed(_:)),
            name: .requestFailed,
            object: nil
        )
    }
    
    private func addLog(_ message: String) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss.SSS"
        let timestamp = dateFormatter.string(from: Date())
        
        logs.append("[\(timestamp)] \(message)")
        tableView.reloadData()
        
        // 滚动到底部
        if logs.count > 0 {
            let indexPath = IndexPath(row: logs.count - 1, section: 0)
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
    
    private func updateDomainIndicator() {
        domainIndicator.text = "当前域名: \(DomainManager.shared.currentDomain)"
    }
    
    // MARK: - 按钮操作
    
    @objc private func fetchUserProfile() {
        addLog("发起请求: 获取用户信息")
        NetworkService.shared.request("/user/profile") { [weak self] (result: Result<UserProfile, AFError>) in
            switch result {
                case .success(let profile):
                    self?.addLog("✅ 用户信息: \(profile.name), 积分: \(profile.points)")
                case .failure(let error):
                    xlog("❌ 用户信息请求失败: \(error.localizedDescription)")
                    self?.addLog("❌ 用户信息请求失败: \(error.localizedDescription)")
            }
        }
    }
    
    @objc private func fetchProducts() {
        addLog("发起请求: 获取商品列表")
        NetworkService.shared.request("/products") { [weak self] (result: Result<[Product], AFError>) in
            switch result {
                case .success(let products):
                    self?.addLog("✅ 获取到 \(products.count) 个商品")
                    if let firstProduct = products.first {
                        self?.addLog("首个商品: \(firstProduct.name), 价格: \(firstProduct.price)")
                    }
                case .failure(let error):
                    self?.addLog("❌ 商品列表请求失败: \(error.localizedDescription)")
            }
        }
    }
    
    @objc private func makeFailingRequest() {
        addLog("发起请求: 模拟失败请求")
        NetworkService.shared.request("/will/fail") { [weak self] (result: Result<String, AFError>) in
            if case .failure(let error) = result {
                self?.addLog("❌ 模拟请求失败: \(error.localizedDescription)")
            }
        }
    }
    
    @objc private func resetDomains() {
        DomainManager.shared.resetAllDomains()
        addLog("已重置所有域名状态")
        updateDomainIndicator()
        
        // 动画效果
        UIView.animate(withDuration: 0.3, animations: {
            self.domainStatusView.backgroundColor = .systemPurple
        }) { _ in
            UIView.animate(withDuration: 0.5) {
                self.domainStatusView.backgroundColor = .secondarySystemBackground
            }
        }
    }
    
    // MARK: - 通知处理
    @objc private func domainSwitched(_ notification: Notification) {
        if let reason = notification.userInfo?["reason"] as? String,
           let domain = notification.userInfo?["domain"] as? String {
            addLog("⚠️ 域名切换: \(reason) → \(domain)")
            
            // 更新域名指示器
            updateDomainIndicator()
            
            // 添加动画效果
            UIView.animate(withDuration: 0.2, animations: {
                self.domainStatusView.backgroundColor = .systemOrange
            }) { _ in
                UIView.animate(withDuration: 0.5) {
                    self.domainStatusView.backgroundColor = .secondarySystemBackground
                }
            }
        }
    }
    
    @objc private func requestSucceeded() {
        updateDomainIndicator()
        UIView.animate(withDuration: 0.3, animations: {
            self.domainStatusView.backgroundColor = .systemGreen
        }) { _ in
            UIView.animate(withDuration: 1.0) {
                self.domainStatusView.backgroundColor = .secondarySystemBackground
            }
        }
    }
    
    @objc private func requestFailed(_ notification: Notification) {
        if let error = notification.userInfo?["error"] as? AFError {
            addLog("❌ 请求失败: \(error.localizedDescription)")
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            self.domainStatusView.backgroundColor = .systemRed
        }) { _ in
            UIView.animate(withDuration: 1.0) {
                self.domainStatusView.backgroundColor = .secondarySystemBackground
            }
        }
    }
    
}

// MARK: - 表格视图
extension MainViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return logs.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LogCell", for: indexPath) as! LogCell
        cell.configure(with: logs[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
}

class LogCell: UITableViewCell {
    private let logLabel = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .clear
        selectionStyle = .none
        
        logLabel.numberOfLines = 0
        logLabel.font = UIFont.monospacedSystemFont(ofSize: 14, weight: .regular)
        contentView.addSubview(logLabel)
        logLabel.translatesAutoresizingMaskIntoConstraints = false
        
        logLabel.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16))
        }
    }
    
    func configure(with text: String) {
        logLabel.text = text
        
        if text.contains("✅") {
            logLabel.textColor = .systemGreen
        } else if text.contains("⚠️") {
            logLabel.textColor = .systemOrange
        } else if text.contains("❌") {
            logLabel.textColor = .systemRed
        } else {
            logLabel.textColor = .label
        }
    }
}

// MARK: - 通知扩展

extension Notification.Name {
    static let domainSwitched = Notification.Name("DomainSwitchedNotification")
    static let requestSucceeded = Notification.Name("RequestSucceededNotification")
    static let requestFailed = Notification.Name("RequestFailedNotification")
}

// MARK: - 数据模型

struct UserProfile: Codable {
    let id: String
    let name: String
    let email: String
    let points: Int
}

struct Product: Codable {
    let id: String
    let name: String
    let price: Double
    let stock: Int
}

